#include <pthread.h>
#include <malloc.h>
#include <string.h>

#include "task_manager.h"
#include "log.h"
#include "core_conf.h"

struct task_manager *task_manager_create(void)
{
	log_info("begin task_manager_create.");
	struct task_manager *task_manager = (struct task_manager *)malloc(sizeof(struct task_manager));
	if (task_manager == NULL) {
		log_error("No enough Mem.");
		return NULL;
	}
	return task_manager;
}

int task_manager_init(struct task_manager *task_manager, struct core_conf *core_conf)
{
	log_info("begin task_manager_init");
	if (task_manager == NULL) {
		return -1;
	}

	int ret = 0;
	ret = pthread_mutex_init(&(task_manager->lock), NULL);
	if (ret != 0) {
		log_error("task_manager_init init failed. err: %d", ret);
	}

	task_manager->count = 0;
	task_manager->task_head = NULL;
	task_manager->core_conf = core_conf;

	return 0;
}

int task_manager_finish(struct task_manager *task_manager)
{
	log_print("task_manager_finish. not implement now.");
	return 0;
}

int task_manager_add_task(struct task_manager *task_manager, struct task *task)
{
	log_info("begin task_manager_add_task.");		
	if (task_manager == NULL || task == NULL) {
		log_error("task_manager is NULL or task is NULL.");
		return -1;
	}

	pthread_mutex_lock(&(task_manager->lock));
	if (task_manager->task_head == NULL) {
		task_manager->task_head = task;
	} else {
		struct task *tmp;
		for (tmp = task_manager->task_head; tmp->next != NULL; tmp = tmp->next) {
			if (strcmp(tmp->task_name, task->task_name) == 0) {
				log_warning("task: %s already loaded.", task->task_name);
				return 0;
			}
		}
		tmp->next = task;
	}
	task_manager->count++;
	log_info("add task: %s.", task->task_name);
	pthread_mutex_unlock(&(task_manager->lock));

	return 0;
}

